﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Shell32;
using System.Data.OleDb;
using System.Diagnostics;

namespace CheckDB
{
    public class AcctionCheckBLL
    {
        private static string pathExe;
        private static string pathDll;
        private static string FileExe;
        private static string FileDll;
        private static string Exe;
        private static string Dll;
        private static string _Path;
        private static string StrConnection;
        private static string OldMdb;
        private int Search = 0;

        public AcctionCheckBLL()
        { }

        public AcctionCheckBLL(int _search, string _path)
        {
            Search = _search;
            _Path = _path;
        }

        public bool CheckProcess(bool soft)
        {
            if (soft)
            {
                Process[] prVK = Process.GetProcessesByName("VietKins");
                if (prVK.Length > 0)
                {
                    MessageBox.Show("Để cập nhật thành công, hãy tắt chương trình VietKins và Click vào 'Cập nhật'!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                    return true;
                }
                return false;
            }
            else
            {
                Process[] prVE = Process.GetProcessesByName("VietEs");
                if (prVE.Length > 0)
                {
                    MessageBox.Show("Để cập nhật thành công, hãy tắt chương trình VietEs và Click vào 'Cập nhật'!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                    return true;
                }
                return false;
            }
        }

        public bool button2_Click()
        {
            MessageBox.Show("Không tìm thấy dữ liệu *.mdb!\nHãy chỉ ra file *.mdb của chương trình!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Microsoft Access Databases (*.mdb)|*.mdb";
            //ofd.Filter = "All Files (*.lnk)|(*.lnk)";
            DialogResult Result = ofd.ShowDialog();
            if (Result == DialogResult.Cancel)
            {
                return true;
            }
            if (System.IO.File.Exists(ofd.FileName))
            {
                StrConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ofd.FileName;
                OldMdb = ofd.FileName;
                return false;
            }
            else
            {
                MessageBox.Show("Không tồn tại đường dẫn file dữ liệu như mô tả.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return true;
        }

        public bool GetShortcutFile(bool Prg)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Shortcut File (*.lnk)|*.lnk";
            //ofd.Filter = "All Files (*.lnk)|(*.lnk)";
            if (Prg)
                ofd.FileName = @"C:\Documents and Settings\All Users\Desktop\VietKins";
            else
                ofd.FileName = @"C:\Documents and Settings\All Users\Desktop\VietEs";
            DialogResult Result = ofd.ShowDialog();
            if (Result == DialogResult.Cancel)
            {
                return true;
            }
            if (System.IO.File.Exists(ofd.FileName))
            {
                if (GetShortcutTargetFile(ofd.FileName, Prg) != "")
                {
                    return false;
                }
            }
            else
            {
                MessageBox.Show("Không tồn tại đường dẫn file dữ liệu như mô tả.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            return true;
        }

        public string GetShortcutTargetFile(string shortcutFilename, bool Prg)
        {
            try
            {
                string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
                string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

                Shell32.Shell shell = new Shell32.ShellClass();
                Shell32.Folder folder = shell.NameSpace(pathOnly);
                Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
                if (folderItem != null)
                {
                    Shell32.ShellLinkObject link =
                    (Shell32.ShellLinkObject)folderItem.GetLink;
                    if (link != null && link.Path != "")
                    {
                        if (Prg)
                        {
                            if (link.WorkingDirectory.EndsWith(@"\"))
                            {
                                if (File.Exists(link.WorkingDirectory + "VietKins.exe"))
                                {
                                    _Path = link.WorkingDirectory;
                                    return _Path;
                                }
                            }
                            else
                            {
                                if (File.Exists(link.WorkingDirectory + @"\VietKins.exe"))
                                {
                                    _Path = link.WorkingDirectory + @"\";
                                    return _Path;
                                }
                            }
                            MessageBox.Show("Không tìm thấy VietKins.exe!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            if (link.WorkingDirectory.EndsWith(@"\"))
                            {
                                if (File.Exists(link.WorkingDirectory + "VietEs.exe"))
                                {
                                    _Path = link.WorkingDirectory;
                                    return _Path;
                                }
                            }
                            else
                            {
                                if (File.Exists(link.WorkingDirectory + @"\VietEs.exe"))
                                {
                                    _Path = link.WorkingDirectory + @"\";
                                    return _Path;
                                }
                            }
                            MessageBox.Show("Không tìm thấy VietEs.exe !", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                return ""; // not found
            }
            catch (Exception e)
            {
                MessageBox.Show("Lỗi GetShortcutTargetFile()\n" + e.Message);
                return "";
            }
        }

        public bool BackUp(bool soft)
        {
            string backUpPath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string nameApp = "VietEs";
            if(soft)
                nameApp = "VietKins";
            try
            {
                if (!Directory.Exists(backUpPath + "\\BackUp"))
                    Directory.CreateDirectory(backUpPath + "\\BackUp");
                if (!Directory.Exists(backUpPath + "\\BackUp\\" + nameApp))
                    Directory.CreateDirectory(backUpPath + "\\BackUp\\" + nameApp);

            }
            catch (Exception e)
            {
                MessageBox.Show("Chưa sao lưu(Create Folder BackUp) được.\n" + e.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            string newDrec = backUpPath + "\\BackUp\\" + nameApp + "\\" + DateTime.Now.ToString().Replace("/", "-").Replace(":", "-");
            try
            {
                Directory.CreateDirectory(newDrec);
            }
            catch (Exception e)
            {
                MessageBox.Show("Chưa sao lưu(Directory.CreateDirectory) được.\n" + e.Message + "\n" + newDrec, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            try
            {
                if (File.Exists(pathExe))
                    File.Copy(pathExe, newDrec + "\\" + Exe);
                if (File.Exists(pathDll))
                    File.Copy(pathDll, newDrec + "\\" + Dll);
                File.Copy(OldMdb, newDrec + "\\ODB.mdb");
            }
            catch (Exception e)
            {
                MessageBox.Show("Chưa sao lưu(Move File) được.\n" + e.Message + "\n" + newDrec + "\n" + "File.Copy(" + OldMdb + "," + newDrec + "\\ODB.mdb)", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            return false;
        }

        public bool SetPath(bool soft)
        {
            if (soft)
            {
                Exe = "VietKins.exe";
                Dll = "Manager.dll";
                FileExe = "Vietkins\\VietKins.exe";
                FileDll = "Vietkins\\Manager.dll";
                pathExe = _Path + "VietKins.exe";
                pathDll = _Path + "Manager.dll";
            }
            else
            {
                Exe = "VietEs.exe";
                Dll = "Manager.dll";
                FileExe = "VietEs\\VietEs.exe";
                FileDll = "VietEs\\Manager.dll";
                pathExe = _Path + "VietEs.exe";
                pathDll = _Path + "Manager.dll";
            }
            if (System.IO.File.Exists(_Path + @"\Logininfo.txt"))
            {
                string str;
                string[] lines = File.ReadAllLines(_Path + @"\Logininfo.txt");
                str = lines[1].Split(new char[] { '|' })[0];
                lines = lines[1].Split(new char[] { '=' });
                OldMdb = lines[2].Remove(lines[2].Length - 1);
                if (lines[2].Contains("|DataDirectory|"))
                {
                    lines = lines[2].Split(new char[] { '|' });
                    str += _Path.Substring(0, _Path.Length - 1) + lines[2].Remove(lines[2].Length - 1);
                    OldMdb = _Path.Substring(0, _Path.Length - 1) + lines[2].Remove(lines[2].Length - 1);
                    if (!System.IO.File.Exists(_Path + lines[2].Remove(lines[2].Length - 1)))
                    {
                        return button2_Click();
                    }
                }
                StrConnection = str;
            }
            else
            {
                return button2_Click();
            }
            return false;
        }

        public void CopyTo(bool soft)
        {
            string outPath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            if (Exe == null || Exe == "")
                SetPath(soft);
            try
            {
                if (File.Exists(pathExe))
                    File.Copy(outPath + @"\ProgramFile\" + FileExe, pathExe, true);
                else
                    File.Move(outPath + @"\ProgramFile\" + FileExe, pathExe);

                if (File.Exists(pathDll))
                    File.Copy(outPath + @"\ProgramFile\" + FileDll, pathDll, true);
                else
                    File.Move(outPath + @"\ProgramFile\" + FileExe, pathDll);
            }
            catch (Exception e)
            {
                MessageBox.Show("Chưa cập nhật Version được(Copy File) được.\n" + e.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool ExpandFolder(string ExpandedFolder, string FileName)
        {
            string outPath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            try
            {
                Shell sc = new Shell();
                if (!Directory.Exists(outPath + @"\ProgramFile"))
                {
                    Directory.CreateDirectory(outPath + @"\ProgramFile");
                }
                else
                {
                    try
                    {
                        DirectoryInfo[] Dirs = new DirectoryInfo(outPath + @"\ProgramFile").GetDirectories();
                        for (int i = 0; i < Dirs.Length; i++)
                        {
                            FileInfo[] Files = new DirectoryInfo(Dirs[i].FullName).GetFiles();
                            foreach (FileInfo file in Files)
                            {
                                file.Delete();
                            }
                            Dirs[i].Delete();
                        }
                    }
                    catch
                    { }
                }
                //'Declare the folder where the files will be extracted
                Folder output = sc.NameSpace(outPath + @"\ProgramFile");
                //'Declare your input zip file as folder  .
                Folder input = sc.NameSpace(appPath + @"\" + FileName);
                //'Extract the files from the zip file using the CopyHere command .
                foreach (FolderItem F in input.Items())
                {
                    output.CopyHere(F, 4);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Chưa giải nén(ExpandFolder) được.\n" + e.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            return false;
        }

        public string GetConnectionString()
        {
            string myConnString = StrConnection;

            try
            {
                OleDbConnection oCon = new OleDbConnection(myConnString);
                oCon.Open();
                ClsConnection.connectString2 = myConnString;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không kết nối được tới cơ sở dữ liệu!\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            return myConnString;
        }

        public DialogResult ShowMessage(string _mss, string _caption)
        {
            return MessageBox.Show(_mss, _caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign);
        }

        public void Complete()
        {
            pathExe = null;
            pathDll = null;
            FileExe = null;
            FileDll = null;
            Exe = null;
            Dll = null;
            _Path = null;
        }
    }
}
